package com.glorysoft.lipuxinpda.activity;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.glorysoft.lipuxinpda.R;
import com.glorysoft.lipuxinpda.adapter.MaterialExchangeScanAdapter;
import com.glorysoft.lipuxinpda.base.BaseActivity;
import com.glorysoft.lipuxinpda.base.Constant;
import com.glorysoft.lipuxinpda.entity.BaseEntity;
import com.glorysoft.lipuxinpda.entity.ChangeMaterialInfoEntity;
import com.glorysoft.lipuxinpda.entity.KeyValueEntity;
import com.glorysoft.lipuxinpda.entity.ShowMaterialInReturnEntity;
import com.glorysoft.lipuxinpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.activity_public.FreeUI_QRCodeActivity;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MaterialExchangeScanActivity extends BaseActivity {
    private Context mContext;

    private LinearLayout llMain;
    private RelativeLayout rl_material_type;

    private FreeUI_ClearEditText et_sn;//物料条码

    private Button btn_scan;//扫描
    private Button btn_confirm;//确定

    private TextView tv_current_eqp_no;//当前设备
    private TextView tv_material_type;//物料类型

    private RecyclerView rv_data;

    private String sEqpID = "";//设备号
    private String sMaterialType = "";//物料类型
    private String sSn = "";//物料条码

    private ShowMaterialInReturnEntity mShowMaterialInReturnEntity;//物料信息
    private ChangeMaterialInfoEntity mChangeMaterialInfoEntity;//更换物料信息

    private FreeUI_GeneralFragmentDialog mMessageDialog;//消息提示框

    private MaterialExchangeScanAdapter mAdapter;
    private List<KeyValueEntity> mKeyValueList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_material_exchange_scan;
    }

    @Override
    protected void initView() {
        mContext = this;

        llMain = findViewById(R.id.llMain);
        rl_material_type = findViewById(R.id.rl_material_type);

        et_sn = findViewById(R.id.et_sn);
        btn_confirm = findViewById(R.id.btn_confirm);

        btn_scan = findViewById(R.id.btn_scan);

        tv_current_eqp_no = findViewById(R.id.tv_current_eqp_no);
        tv_material_type = findViewById(R.id.tv_material_type);

        rv_data = findViewById(R.id.rv_data);

        et_sn.requestFocus();

        btn_scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, FreeUI_QRCodeActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent, 103);
            }
        });

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (et_sn.getText().toString().equals("")){
                    showToast(getResources().getString(R.string.please_input_material_sn), false);
                }else {
                      getMaterialIn();//获取物料信息

                    //region 测试
//                    showMaterialIn();//显示物料信息
                    //endregion
                }
            }
        });
    }

    @Override
    protected void initData() {
        sEqpID = getIntent().getStringExtra("EQPID");
        sMaterialType = getIntent().getStringExtra("MATERIALTYPE");
        tv_current_eqp_no.setText(sEqpID);

        mKeyValueList = new ArrayList<>();
//        //region 测试
//        KeyValueEntity keyValueEntity1 = new KeyValueEntity();
//        keyValueEntity1.setID_CH("规格");
//        keyValueEntity1.setVALUE("上等");
//        KeyValueEntity keyValueEntity2 = new KeyValueEntity();
//        keyValueEntity2.setID_CH("供应商");
//        keyValueEntity2.setVALUE("xxx");
//        KeyValueEntity keyValueEntity3 = new KeyValueEntity();
//        keyValueEntity3.setID_CH("批号");
//        keyValueEntity3.setVALUE("00000");
//        mKeyValueList.add(keyValueEntity1);
//        mKeyValueList.add(keyValueEntity2);
//        mKeyValueList.add(keyValueEntity3);
        //endregion
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle(getString(R.string.materialReplacement));
        freeUI_titleView.setRightListener(getString(R.string.replace), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ChangeMaterialInfo();//更换物料
//                sSn = et_sn.getText().toString();
//                // region 测试
//                if (sSn.equals("111")) {
//                    Intent intent = new Intent();
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable("list", (Serializable)mKeyValueList);
//                    intent.putExtras(bundle);
//                    setResult(-2, intent);
//                    showMessageDialog("更换成功");
//                } else {
//                    showMessageDialog("更换失败");
//                }

                // endregion
            }
        });
        return new FreeUI_AddViewEntity(getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY), llMain);
    }

    //region 接口调用

    //更换物料
    private void ChangeMaterialInfo() {
        FreeUI_EntityCallBack<BaseEntity> callBack = new FreeUI_DialogEntityCallBack<BaseEntity>(new TypeToken<BaseEntity>() {
        }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseEntity> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getSupportFragmentManager())) {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("list", (Serializable) mKeyValueList);
                    intent.putExtras(bundle);
                    setResult(-2, intent);
                }
                if (!TextUtils.isEmpty(response.body().getMessage())) {
                    showMessageDialog(response.body().getMessage());
                }
            }

            @Override
            public void onError(Response<BaseEntity> response) {
                super.onError(response);
                loadError(response.getException(), "ChangeMaterialInfo");
            }
        };

        HashMap<String, String> map = new HashMap<String, String>();

        map.put("EQP_ID", sEqpID);//设备号
        map.put("CUR_USERID", Constant.INSTANCE.getLoginEntity().getWORK_NO());//工号
        mChangeMaterialInfoEntity = new ChangeMaterialInfoEntity();
        mChangeMaterialInfoEntity.setMATERIALTYPE(mShowMaterialInReturnEntity.getMATERIALTYPE());
        mChangeMaterialInfoEntity.setMATERIAL_PN(mShowMaterialInReturnEntity.getMATERIAL_PN());
        mChangeMaterialInfoEntity.setMATERIALLOTNO(mShowMaterialInReturnEntity.getMATERIALLOTNO());
        Gson gson = new Gson();
        String sJson = gson.toJson(mChangeMaterialInfoEntity);
        map.put("YZ1_MATERIALINFO", sJson);//要更换的物料信息
        String method = Constant.INSTANCE.getNET_URL() + "/ChangeMaterialInfo";
        new NetUtils().requestPostNetNews(method, this, map, callBack);
    }


    //获取物料信息
    private void getMaterialIn() {
        FreeUI_EntityCallBack<BaseEntity<ShowMaterialInReturnEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseEntity<ShowMaterialInReturnEntity>>(new TypeToken<BaseEntity<ShowMaterialInReturnEntity>>() {
        }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseEntity<ShowMaterialInReturnEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getSupportFragmentManager())) {
                    showToast(response.body().getMessage(), true);
                    mShowMaterialInReturnEntity = response.body().getData().getBody();

                    //region 获取实体类变量名，变量值
                    if (mKeyValueList != null && mKeyValueList.size() > 0) {
                        mKeyValueList.clear();
                    }
                    Field[] fields = mShowMaterialInReturnEntity.getClass().getDeclaredFields();
                    for (Field field : fields) {
                        //对于每个属性，获取属性名
                        String varName = field.getName();
                        try {
                            boolean access = field.isAccessible();
                            if (!access)
                                field.setAccessible(true);
                            //从obj中获取field变量
                            Object o = field.get(mShowMaterialInReturnEntity);
                            if (String.valueOf(o).equals("")){
                                break;
                            }
                            KeyValueEntity keyValueEntity = new KeyValueEntity();
                            keyValueEntity.setID_CH(varName);
                            keyValueEntity.setVALUE(String.valueOf(o));
                            mKeyValueList.add(keyValueEntity);
//                            System.out.println("变量： " + varName + " = " + o);
                            if (!access) field.setAccessible(false);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                    //endregion

                    showMaterialIn();//显示物料信息
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<ShowMaterialInReturnEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "ShowMaterialIn");
            }
        };

        HashMap<String, String> map = new HashMap<String, String>();

        map.put("EQP_ID", sEqpID);//设备号
        map.put("CUR_USERID", Constant.INSTANCE.getLoginEntity().getWORK_NO());//工号
        map.put("MATERIALCODE", sSn);//物料条码
        map.put("MATERIALTYPE", sMaterialType);//物料类型
        String method = Constant.INSTANCE.getNET_URL() + "/ShowMaterialIn";
        new NetUtils().requestPostNetNews(method, this, map, callBack);
    }

    //endregion

    //显示物料信息
    private void showMaterialIn() {
        if (mKeyValueList.size() > 0) {
            mAdapter = new MaterialExchangeScanAdapter();
            mAdapter.setData(mKeyValueList);

            //竖直排列、正向排序
            rv_data.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
            rv_data.setAdapter(mAdapter);

            mShowMaterialInReturnEntity = new ShowMaterialInReturnEntity();
            mShowMaterialInReturnEntity.setMATERIALTYPE("测试");
            tv_material_type.setText(mShowMaterialInReturnEntity.getMATERIALTYPE());
            rl_material_type.setVisibility(View.VISIBLE);
        }
    }

    //消息提示框
    private void showMessageDialog(String message) {
        mMessageDialog = new FreeUI_GeneralFragmentDialog();
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_prompt, null);
        Button btnConfirm = view.findViewById(R.id.btnConfirm);
        TextView tvTips = view.findViewById(R.id.tvTips);
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMessageDialog.dismiss();
            }
        });
        tvTips.setText(message);
        mMessageDialog.setLayout(view);
//        mDieTypeDialog.getDialog().setCanceledOnTouchOutside(false);
        mMessageDialog.show(getSupportFragmentManager(), "ShowMessage");
        mMessageDialog.setCallBack(new FreeUI_CommonCallback() {
            @Override
            public void onSuccess() {
                mMessageDialog = null;
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            if (data != null) {
                String barCode = data.getStringExtra("barCode");
                et_sn.setText(barCode);
                et_sn.setSelection(barCode.length());
                sSn = et_sn.getText().toString();
                getMaterialIn();//获取物料信息

                //region 测试
//                showMaterialIn();//显示物料信息
                //endregion
            }
        }
    }
}